<template>
  <div class="fuel-stats-management">
    <!-- 筛选和搜索栏 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-group">
          <label for="vehicle-filter">车辆</label>
          <select
            id="vehicle-filter"
            v-model="filters.vehicle_id"
            @change="fetchStats"
          >
            <option value="">全部车辆</option>
            <option
              v-for="vehicle in vehicles"
              :key="vehicle.id"
              :value="vehicle.id"
            >
              {{ vehicle.name }}
            </option>
          </select>
        </div>

        <div class="filter-group">
          <label for="start-date">开始日期</label>
          <input
            id="start-date"
            v-model="filters.start_date"
            type="date"
            @change="fetchStats"
          />
        </div>

        <div class="filter-group">
          <label for="end-date">结束日期</label>
          <input
            id="end-date"
            v-model="filters.end_date"
            type="date"
            @change="fetchStats"
          />
        </div>
      </div>
    </div>

    <!-- 主要统计卡片 -->
    <div v-if="fuelStats" class="main-stats">
      <div class="stats-grid">
        <div class="stat-card primary">
          <div class="stat-icon">📊</div>
          <div class="stat-content">
            <div class="stat-label">平均油耗</div>
            <div class="stat-value">
              {{ fuelStats.avg_fuel_consumption.toFixed(2) }}
              <span class="unit">L/100km</span>
            </div>
          </div>
        </div>

        <div class="stat-card success">
          <div class="stat-icon">💰</div>
          <div class="stat-content">
            <div class="stat-label">总加油费用</div>
            <div class="stat-value">
              ¥{{ fuelStats.total_fuel_cost.toFixed(2) }}
            </div>
          </div>
        </div>

        <div class="stat-card info">
          <div class="stat-icon">⛽</div>
          <div class="stat-content">
            <div class="stat-label">总加油量</div>
            <div class="stat-value">
              {{ fuelStats.total_fuel_amount.toFixed(2) }}
              <span class="unit">升</span>
            </div>
          </div>
        </div>

        <div class="stat-card warning">
          <div class="stat-icon">🛣️</div>
          <div class="stat-content">
            <div class="stat-label">总行驶里程</div>
            <div class="stat-value">
              {{ fuelStats.total_distance.toFixed(0) }}
              <span class="unit">km</span>
            </div>
          </div>
        </div>
      </div>

      <div class="stats-grid secondary">
        <div class="stat-card">
          <div class="stat-icon">📝</div>
          <div class="stat-content">
            <div class="stat-label">记录数量</div>
            <div class="stat-value">{{ fuelStats.record_count }}</div>
          </div>
        </div>

        <div class="stat-card">
          <div class="stat-icon">💵</div>
          <div class="stat-content">
            <div class="stat-label">平均油价</div>
            <div class="stat-value">
              ¥{{ fuelStats.avg_fuel_price.toFixed(2) }}
              <span class="unit">/升</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <div v-else-if="!loading && !fuelStats" class="empty-state">
      <svg
        width="64"
        height="64"
        viewBox="0 0 24 24"
        fill="none"
        stroke="currentColor"
        stroke-width="1"
      >
        <path
          d="M9 11H3v10h6V11zm4-7H7v17h6V4zm4 3h-6v14h6V7zm4-6h-6v20h6V1z"
        />
        <path d="M9 2v2m6-2v2m6-2v2" />
      </svg>
      <p>暂无统计数据</p>
      <p class="empty-hint">请先添加加油记录以查看统计信息</p>
    </div>

    <!-- 加载状态 -->
    <div v-else-if="loading" class="loading-state">
      <div class="loading-spinner"></div>
      <p>加载统计数据中...</p>
    </div>

    <!-- 费用汇总 -->
    <div v-if="costSummary" class="cost-summary-section">
      <h3>费用汇总</h3>
      <div class="cost-summary-grid">
        <div class="cost-item">
          <span class="cost-label">总费用:</span>
          <span class="cost-value"
            >¥{{ costSummary.total_cost?.toFixed(2) || "0.00" }}</span
          >
        </div>
        <div class="cost-item">
          <span class="cost-label">月均费用:</span>
          <span class="cost-value"
            >¥{{ costSummary.monthly_average?.toFixed(2) || "0.00" }}</span
          >
        </div>
        <div class="cost-item">
          <span class="cost-label">日均费用:</span>
          <span class="cost-value"
            >¥{{ costSummary.daily_average?.toFixed(2) || "0.00" }}</span
          >
        </div>
      </div>
    </div>

    <!-- 车辆对比 -->
    <div v-if="vehiclesWithStats.length > 0" class="vehicle-comparison-section">
      <h3>车辆对比</h3>
      <div class="vehicle-comparison-grid">
        <div
          v-for="vehicleWithStats in vehiclesWithStats"
          :key="vehicleWithStats.vehicle.id"
          class="vehicle-comparison-card"
        >
          <div class="vehicle-header">
            <h4>{{ vehicleWithStats.vehicle.name }}</h4>
            <span
              class="vehicle-status"
              :class="{ active: vehicleWithStats.vehicle.is_active }"
            >
              {{ vehicleWithStats.vehicle.is_active ? "使用中" : "已停用" }}
            </span>
          </div>

          <div class="vehicle-stats">
            <div class="vehicle-stat-item">
              <span class="stat-label">油耗</span>
              <span class="stat-value">
                {{
                  vehicleWithStats.fuel_stats?.avg_fuel_consumption?.toFixed(
                    2,
                  ) || "N/A"
                }}
                L/100km
              </span>
            </div>
            <div class="vehicle-stat-item">
              <span class="stat-label">总费用</span>
              <span class="stat-value">
                ¥{{
                  vehicleWithStats.fuel_stats?.total_fuel_cost?.toFixed(2) ||
                  "0.00"
                }}
              </span>
            </div>
            <div class="vehicle-stat-item">
              <span class="stat-label">记录数</span>
              <span class="stat-value">
                {{ vehicleWithStats.fuel_stats?.record_count || 0 }}
              </span>
            </div>
          </div>

          <div v-if="vehicleWithStats.latest_fuel_record" class="latest-record">
            <div class="latest-record-header">
              <span class="latest-label">最新记录</span>
              <span class="latest-date">{{
                formatDate(vehicleWithStats.latest_fuel_record.refuel_date)
              }}</span>
            </div>
            <div class="latest-record-details">
              <span
                >{{
                  vehicleWithStats.latest_fuel_record.fuel_amount.toFixed(2)
                }}升</span
              >
              <span
                >¥{{
                  vehicleWithStats.latest_fuel_record.fuel_cost.toFixed(2)
                }}</span
              >
              <span
                >{{
                  vehicleWithStats.latest_fuel_record.current_mileage.toFixed(
                    0,
                  )
                }}km</span
              >
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 趋势图表 -->
    <div v-if="fuelStats && fuelStats.record_count > 0" class="trend-section">
      <h3>油耗趋势</h3>
      <div class="trend-chart">
        <div class="chart-placeholder">
          <svg width="100%" height="200" viewBox="0 0 400 200">
            <!-- 简单的图表占位符 -->
            <rect
              x="50"
              y="20"
              width="300"
              height="160"
              fill="none"
              stroke="var(--border-primary)"
              stroke-width="2"
              rx="8"
            />
            <text
              x="200"
              y="100"
              text-anchor="middle"
              fill="var(--text-secondary)"
              font-size="14"
            >
              图表功能开发中...
            </text>
          </svg>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { useVehicleStore } from "@/stores/vehicle";
import type {
  VehicleResponse,
  VehicleWithFuelStats,
  FuelConsumptionStats,
  FuelConsumptionStatsParams,
} from "@/types/vehicle";

// 车辆store
const vehicleStore = useVehicleStore();

// 响应式状态
const vehicles = ref<VehicleResponse[]>([]);
const vehiclesWithStats = ref<VehicleWithFuelStats[]>([]);
const fuelStats = ref<FuelConsumptionStats | null>(null);
const costSummary = ref<{
  total_cost?: number;
  monthly_average?: number;
  daily_average?: number;
} | null>(null);
const loading = ref(false);

// 筛选条件
const filters = reactive<FuelConsumptionStatsParams>({
  vehicle_id: undefined,
  start_date: undefined,
  end_date: undefined,
});

// 获取车辆列表
const fetchVehicles = async () => {
  try {
    const response = await vehicleStore.fetchVehicles();
    vehicles.value = response.vehicles;
  } catch (error) {
    console.error("获取车辆列表失败:", error);
  }
};

// 获取带统计的车辆列表
const fetchVehiclesWithStats = async () => {
  try {
    vehiclesWithStats.value = await vehicleStore.fetchVehiclesWithStats();
  } catch (error) {
    console.error("获取车辆统计列表失败:", error);
  }
};

// 获取油耗统计
const fetchStats = async () => {
  try {
    loading.value = true;
    fuelStats.value = await vehicleStore.fetchFuelStats(filters);

    // 获取费用汇总
    const costFilters = {
      start_date: filters.start_date || undefined,
      end_date: filters.end_date || undefined,
      vehicle_id: filters.vehicle_id || undefined,
    };
    costSummary.value = await vehicleStore.fetchFuelCostSummary(costFilters);
  } catch (error) {
    console.error("获取油耗统计失败:", error);
  } finally {
    loading.value = false;
  }
};

// 格式化日期
const formatDate = (dateString: string): string => {
  return new Date(dateString).toLocaleDateString("zh-CN");
};

// 设置默认日期范围（最近30天）
const setDefaultDateRange = () => {
  const endDate = new Date();
  const startDate = new Date();
  startDate.setDate(endDate.getDate() - 30);

  filters.end_date = endDate.toISOString().split("T")[0];
  filters.start_date = startDate.toISOString().split("T")[0];
};

// 组件挂载时获取数据
onMounted(async () => {
  setDefaultDateRange();
  await Promise.all([fetchVehicles(), fetchVehiclesWithStats(), fetchStats()]);
});
</script>

<style scoped lang="scss">
@use "@/styles/mixins" as *;

.fuel-stats-management {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.filter-section {
  margin-bottom: 24px;
  padding: 20px;
  @include glass-morphism;
  border-radius: 12px;
}

.filter-row {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.filter-group {
  label {
    display: block;
    margin-bottom: 6px;
    font-size: 14px;
    font-weight: 500;
    color: var(--text-primary);
  }

  select,
  input {
    @include macos-input;
    width: 100%;
  }
}

.main-stats {
  margin-bottom: 32px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 16px;
  margin-bottom: 16px;

  &.secondary {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  }
}

.stat-card {
  @include glass-morphism;
  border-radius: 12px;
  padding: 24px;
  display: flex;
  align-items: center;
  gap: 16px;
  transition: all 0.3s ease;

  &:hover {
    @include hover-lift;
  }

  &.primary {
    border-left: 4px solid var(--theme-primary);
  }

  &.success {
    border-left: 4px solid var(--theme-success);
  }

  &.info {
    border-left: 4px solid var(--theme-primary);
  }

  &.warning {
    border-left: 4px solid var(--theme-warning);
  }
}

.stat-icon {
  font-size: 28px;
  width: 56px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: var(--bg-secondary);
  border-radius: 16px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: var(--text-primary);

  .unit {
    font-size: 14px;
    font-weight: 400;
    color: var(--text-secondary);
    margin-left: 4px;
  }
}

.empty-state {
  text-align: center;
  padding: 80px 20px;
  color: var(--text-secondary);

  svg {
    margin-bottom: 24px;
    opacity: 0.5;
  }

  p {
    margin-bottom: 8px;
    font-size: 18px;
  }

  .empty-hint {
    font-size: 14px;
    opacity: 0.8;
  }
}

.loading-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-secondary);

  .loading-spinner {
    width: 48px;
    height: 48px;
    margin: 0 auto 20px;
    border: 4px solid var(--border-primary);
    border-top: 4px solid var(--theme-primary);
    border-radius: 50%;
    animation: spin 1s linear infinite;
  }
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.cost-summary-section {
  margin-bottom: 32px;
  padding: 24px;
  @include glass-morphism;
  border-radius: 12px;

  h3 {
    margin: 0 0 20px 0;
    font-size: 20px;
    font-weight: 600;
    color: var(--text-primary);
  }
}

.cost-summary-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.cost-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: var(--bg-secondary);
  border-radius: 8px;

  .cost-label {
    font-size: 14px;
    color: var(--text-secondary);
  }

  .cost-value {
    font-size: 18px;
    font-weight: 600;
    color: var(--text-primary);
  }
}

.vehicle-comparison-section {
  margin-bottom: 32px;

  h3 {
    margin: 0 0 20px 0;
    font-size: 20px;
    font-weight: 600;
    color: var(--text-primary);
  }
}

.vehicle-comparison-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
}

.vehicle-comparison-card {
  @include glass-morphism;
  border-radius: 12px;
  padding: 20px;
  transition: all 0.3s ease;

  &:hover {
    @include hover-lift;
  }
}

.vehicle-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  h4 {
    margin: 0;
    font-size: 16px;
    font-weight: 600;
    color: var(--text-primary);
  }

  .vehicle-status {
    font-size: 12px;
    padding: 4px 8px;
    border-radius: 4px;
    font-weight: 500;

    &.active {
      background: var(--theme-success);
      color: white;
    }

    &:not(.active) {
      background: var(--theme-warning);
      color: white;
    }
  }
}

.vehicle-stats {
  display: grid;
  grid-template-columns: 1fr;
  gap: 12px;
  margin-bottom: 16px;
}

.vehicle-stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: var(--bg-secondary);
  border-radius: 6px;

  .stat-label {
    font-size: 12px;
    color: var(--text-secondary);
  }

  .stat-value {
    font-size: 14px;
    font-weight: 500;
    color: var(--text-primary);
  }
}

.latest-record {
  border-top: 1px solid var(--border-primary);
  padding-top: 16px;

  .latest-record-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;

    .latest-label {
      font-size: 12px;
      color: var(--text-secondary);
    }

    .latest-date {
      font-size: 12px;
      color: var(--text-secondary);
    }
  }

  .latest-record-details {
    display: flex;
    justify-content: space-between;
    align-items: center;

    span {
      font-size: 13px;
      color: var(--text-primary);
      font-weight: 500;
    }
  }
}

.trend-section {
  margin-bottom: 32px;

  h3 {
    margin: 0 0 20px 0;
    font-size: 20px;
    font-weight: 600;
    color: var(--text-primary);
  }
}

.trend-chart {
  @include glass-morphism;
  border-radius: 12px;
  padding: 20px;
  height: 240px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.chart-placeholder {
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
}

@include mobile {
  .filter-row {
    grid-template-columns: 1fr;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }

  .cost-summary-grid {
    grid-template-columns: 1fr;
  }

  .vehicle-comparison-grid {
    grid-template-columns: 1fr;
  }

  .vehicle-stats {
    grid-template-columns: 1fr;
  }

  .latest-record-details {
    flex-direction: column;
    gap: 4px;
    align-items: flex-start;
  }
}
</style>
